<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue File Upload to OSS</title>
    <script src="js/vue.js"></script>
    <script src="js/axios.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link rel="stylesheet" href="css/index.css">
</head>
<body>
<div id="app">
    <div class="upload-container"
         @dragover.prevent="handleDragOver"
         @dragleave.prevent="handleDragLeave"
         @drop.prevent="handleDrop"
         :class="{ 'dragover': isDragOver }">
        <input type="file" class="upload-input" ref="fileInput" @change="handleFileSelect" multiple>
        <label class="upload-label" @click="triggerFileSelect">拖拽文件到这里或点击上传</label>
    </div>
    <button class="upload-button" @click="uploadFiles">上传文件</button>
    <div v-if="uploadedUrls!=null" class="uploaded-urls">
        <h3>上传成功的URL:</h3>
        <div>
            <a :href="uploadedUrls" target="_blank">{{ uploadedUrls }}</a>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            isDragOver: false,
            files: [],
            uploadedUrls:''
        },
        methods: {
            handleDragOver() {
                this.isDragOver = true;
            },
            handleDragLeave() {
                this.isDragOver = false;
            },
            handleDrop(event) {
                this.isDragOver = false;
                this.files = Array.from(event.dataTransfer.files);
                alert("文件已经选择");
            },
            handleFileSelect(event) {
                this.files = Array.from(event.target.files);
                alert("文件已经选择");
            },
            triggerFileSelect() {
                this.$refs.fileInput.click();
            },
            async uploadFiles() {
                const formData = new FormData();
                this.files.forEach(file => {
                    formData.append('files', file);
                });

                try {
                    const response = await axios.post('fileinput.do?op=addFiles', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    });
                    const jm = response.data;
                    if (jm.code === 1) {
                        this.uploadedUrls = jm.obj;
                        alert("上传成功");
                    } else {
                        this.uploadedUrls = [];
                        alert("上传失败");
                    }

                } catch (error) {
                    console.error('Upload failed:', error);
                }
            }
        }
    });
</script>
</body>
</html>
